<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021/12/22
 * Time: 10:52
 */
namespace app\index\service;

use think\Exception;
use think\facade\Cache;

class Push{

    private $baseUrl;
    private $appId;
    private $appKey;
    private $mastersecret;


    public function __construct(){
        $config=config('system.geTui');
        $this->appId=$config['appId'];//应用id
        $this->appKey=$config['appKey'];
        $this->mastersecret=$config['masterSecret'];
        //获取个推的配置
        $this->baseUrl = "https://restapi.getui.com/v2/$this->appId";
    }


    /**
     * @return bool|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    private function authToken(){
        $tokenCache=Cache::store('redis')->get('push_token');
        if($tokenCache){
            //说明token还存在,没有过期
            return $tokenCache;
        }else{
            //说明token不存在了，需要从远程获取token
            $authUrl=$this->baseUrl . '/auth';
            $timestamp = millisecond();
            $param['sign'] = $this->encrypt_sha256($this->appKey.$timestamp.$this->mastersecret);
            $param['timestamp'] = $timestamp;
            $param['appkey'] = $this->appKey;
            $result=http_post_json($authUrl,$param);
            $result=json_decode($result,true);
            if($result['code'] === 0){
                //说明成功返回token了
                Cache::store('redis')->set('push_token',$result['data']['token'],60);
                return $result['data']['token'];
            }
            return false;
        }
    }


    /**
     * hash256
     * @param string $str
     * @return string
     */
    private function encrypt_sha256($str = ''){
        return hash("sha256", $str);
    }


    /**
     * @param $cid
     * @param $title
     * @param $body
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function toSingleByCid($cid,$title,$body){
        $param['request_id'] = snowflake();
        $param['audience']=['cid'=>[$cid]];
        $param['settings']=[
            'ttl'=>3 * 24 * 3600 * 1000,//离线时间
            'strategy'=>[
                'default'=>1,
                'ios'=>2,
            ]
        ];
        $param['push_message']=[
            'notification'=>[
                'title'=>$title,
                'body'=>$body,
                'click_type'=>'payload',//点击类型
                'channel_id'=>'Push',
                'channel_name'=>'Push',
                'channel_level'=>4,//设置通知渠道重要性（可以控制响铃，震动，浮动，闪灯等等）
                'payload'=>json_encode(['title'=>$title,'content'=>$body]),//点击通知时，附加自定义透传消息，长度 ≤ 3072
            ]
        ];
        $param['push_channel']=[
            'android'=>[
                'ups'=>[
                    'notification'=>[
                        'title'=>$title,
                        'body'=>$body,
                        'click_type'=>'startapp',//点击类型
                    ]
                ]
            ],
            'ios'=>[
                'type'=>'notify',
                'payload'=>json_encode(['title'=>$title,'content'=>$body]),
                'aps'=>[
                    'alert'=>[
                        'title'=>$title,
                        'body'=>$body
                    ],
                    'content-available'=>0,
                    'sound'=>'default'
                ],
                'auto_badge'=>'+0'
            ]
        ];

        //调用远程接口
        $singleUrl=$this->baseUrl."/push/single/cid";
        $result=http_post_json($singleUrl,$param,$this->authToken());
        return json_decode($result,true);
    }




}